package com.sqfw.project.utils;

import org.apache.tika.Tika;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 检测文件内容
 * @author tangxt
 * @date 2025-10-11
 * */
public class TikaFileValidator {

    private static final Tika tika = new Tika();

    /**
     * 使用Tika检测文件真实类型
     */
    public static boolean validateWithTika(MultipartFile file, String expectedMimeType)
            throws IOException {
        String detectedMimeType = tika.detect(file.getInputStream());
        return expectedMimeType.equalsIgnoreCase(detectedMimeType);
    }

    /**
     * 验证文件扩展名与内容是否匹配
     */
    public static boolean validateFileExtension(MultipartFile file)
            throws IOException {

        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return false;
        }

        String fileExtension = getFileExtension(originalFilename);
        String detectedMimeType = tika.detect(file.getInputStream());

        // 根据MIME类型推断扩展名
        String inferredExtension = getExtensionFromMimeType(detectedMimeType);

        return fileExtension.equalsIgnoreCase(inferredExtension);
    }

    private static String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf(".");
        if (lastDotIndex == -1) {
            return "";
        }
        return filename.substring(lastDotIndex + 1).toLowerCase();
    }

    private static String getExtensionFromMimeType(String mimeType) {
        switch (mimeType) {
            case "image/jpeg":
                return "jpg";
            case "image/png":
                return "png";
            case "application/pdf":
                return "pdf";
            case "application/msword":
                return "doc";
            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                return "docx";
            case "application/vnd.ms-excel":
                return "xls";
            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                return "xlsx";
            case "application/zip":
                return "zip";
            case "text/plain":
                return "txt";
            default:
                return "unknown";
        }
    }


}
